
import sys
#import cv2
#import numpy as np

from common.utils import *
import os
import json
import shutil
from defconfig import *

config['progname'] = progname

def get_model_pa():
    pas = os.path.dirname(__file__).replace('\\', '/').split('/')
    pa = '\\'.join(pas[:-2] + pas[-1:])
    return pa

def get_max_disk():
    import shutil
    disks = 'CDEFG'
    tt = []
    for d in disks:
        try:
            total, used, free = shutil.disk_usage(f'{d}:')
            #logger.info(total, used, free)
            tt.append(total)
        except Exception as e:
            break
    i = np.argmax(tt)
    return disks[i]

def get_out_img_p0():
    D = get_max_disk()
    out_img_p = f'{D}:/data/save/{progname}'
    return out_img_p

out_img_p = get_out_img_p0()
mkdir(out_img_p)

def get_out_img_p():
    d = get_date_stamp()
    outp = f'{out_img_p}/{d}'
    mkdir(outp)
    return outp

def get_outp(index, end):
    d = get_date_stamp()
    aa = 'NG' if end else 'OK'
    outp = f'{out_img_p}/{d}/{aa}'
    mkdir(outp)
    return outp

config_fn = f'{out_img_p}/config.json'

for x in confdef:
    config[x] = confdef[x][1]


def config_load(fn = config_fn):
    try:
        d = json.load(open(fn, 'r'))
        return d
    except Exception as e:
        pass

    return {}

def config_save(fn = config_fn):
    json.dump(config, open(fn, 'w'))

if not os.path.exists(config_fn):
    config_save()

config.update(config_load())
logger.info(config)

tongji = {
    'cnt_ng': 0,
    'cnt_ok': 0,
    'cnt_all': 0,
}

def update_tongji(end):
    tongji['cnt_all'] += 1
    if end:
        tongji['cnt_ng'] += 1
    else:
        tongji['cnt_ok'] += 1

    return 0

def get_logger():
    from logging.handlers import TimedRotatingFileHandler
    log_fmt = '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'
    formatter = logging.Formatter(log_fmt)
    t = str(time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()))
    out_p = get_out_img_p()
    fh = TimedRotatingFileHandler(
        filename="%s/run_%s_%s.log" % (out_p, progname, t),
        when="H", interval=1,
        backupCount=72)
    fh.setFormatter(formatter)
    logging.basicConfig(level=logger.info)
    log = logging.getLogger()
    log.addHandler(fh)
    return log

get_logger()

if __name__ == "__main__":
    pa = 'D:/data/220329竹筷/pic'
    pa = 'D:/data/220329竹筷'
    #del_last_img()
    # cv2.destroyAllWindows()
